//
//  ViewController.m
//  WebJs
//
//  Created by lizq on 16/9/1.
//  Copyright © 2016年 lizq. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "WKWebViewController.h"

#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "UIImage+Ext.h"
#import "CAAnimation+Ext.h"

@interface ViewController () <UIWebViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ABPeoplePickerNavigationControllerDelegate,CAAnimationDelegate>
@property(nonatomic,strong)UIWebView  *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *image = [[UIImage alloc] init];
    image.layer = [CALayer new];
    image.keyWord = @"my key word";
    UIImage *img = [image copy];
    NSLog(@"image 's keyword is %@",image.keyWord);
    NSLog(@"img 's   keyword is %@",img.keyWord);
    NSLog(@"image 's keyword is %p",image.keyWord);
    NSLog(@"img 's   keyword is %p",img.keyWord);
    NSLog(@"image 's layer is %@",image.layer);
    NSLog(@"img 's   layer is %@",img.layer);
    CALayer *layer = [CALayer new];
    layer.bounds = CGRectMake(0, 0, 20, 20);
    layer.position = self.view.center;
    layer.backgroundColor = [UIColor grayColor].CGColor;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
    animation.fromValue = [NSNumber numberWithFloat:self.view.center.y];
    animation.toValue  = @50;
    animation.duration = 10;
    animation.delegate = self;
    animation.layer = layer;
    [self.view.layer addSublayer:layer];
    NSLog(@"animation befor point is %p",animation);
    NSLog(@"animation befor layer is %p",animation.layer);
    [layer addAnimation:animation forKey:@"position"];
    CAAnimation *tmp = [animation copy];
    NSLog(@"tmp 's point is %p",tmp);
    NSLog(@"tmp 's layer point is %p",tmp.layer);
//    [self addImageView];
//    [self.view addSubview:self.webView];
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"js" ofType:@"html"];
//    NSURL *url = [NSURL fileURLWithPath:path];
//    NSURLRequest *requst = [[NSURLRequest alloc] initWithURL:url];
//    [self.webView loadRequest:requst];
//    NSString *js = [NSString stringWithFormat:@"function action(operation) { open(\"action::\" + operation); }"];
//    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if(flag) {
        NSLog(@"animation after point is %p",anim);
        NSLog(@"animation layer point is %p",anim.layer);
        CALayer *layer = anim.layer;
        [layer removeAllAnimations];
    }
}


- (void)addImageView {
    UIImage *image = [UIImage imageNamed:@"dish"];
    UIImageView *view = [[UIImageView alloc] init];
    view.frame = self.view.bounds;
    view.image = image;
    [self.view addSubview:view];
    UIImageView *color = [[UIImageView alloc] init];
    color.frame = CGRectMake(0, 0, self.view.frame.size.width, 100);
    color.backgroundColor = [image themeColor];
    [self.view addSubview:color];
}

- (UIWebView *)webView {
    if(!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        _webView.delegate = self;
    }
    return _webView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark ---
#pragma mark web delegate

- (void)webViewDidStartLoad:(UIWebView *)webView {
    //开始加载
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //加载完成
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    //加载失败
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *path = [[request URL] absoluteString];
    if([path hasPrefix:@"action::"]) {
        NSArray *components = [path componentsSeparatedByString:@"::"];
        NSString *method = [components objectAtIndex:1];
        SEL sel = NSSelectorFromString(method);
        if([self respondsToSelector:sel]) {
            [self performSelector:sel withObject:nil];
        }else {
            NSLog(@"no '%@' method",method);
        }
        return YES;
    }
    return YES;
}

- (void)gotoWKWebView {
    WKWebViewController *vc = [[WKWebViewController alloc] init];
    [self presentViewController:vc animated:YES completion:^{
        
    }];
}

#pragma mark ---
#pragma mark address book

- (void)addressBook {
    ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
    nav.peoplePickerDelegate = self;
    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
    [self presentViewController:nav animated:YES completion:nil];
}

/**
 * cancel
 */
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}


/**
 * select person property
 */
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    // person name
    ABMultiValueRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    ABMultiValueRef lastName =  ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSString *personName = [NSString stringWithFormat:@"%@%@",(__bridge NSString *)lastName,(__bridge NSString *)firstName];
    // person tel
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showPersonTel('%@','%@')",personName,phoneNO]];
    // check tel
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

/**
 * select person
 */
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}



#pragma mark ---
#pragma mark js method

- (void)camera {
    
    UIAlertController *alert = [[UIAlertController alloc] init];
    alert.title = @"选择";
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera:1];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera:2];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)openCamera:(NSInteger)type {
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = type == 1?UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
    NSString *js = [NSString stringWithFormat:@"webAction('%@')",imageSource];
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

@end
